# 11.3 I18nInterceptor

The I18nInterceptor is a component provided for web applications to handle internationalization. Below is an example of how to use it in a Freemarker template:

# Configuration

First, configure I18nInterceptor as a global interceptor.

public void configInterceptor(Interceptors me) {
  me.add(new I18nInterceptor());
}
1
2
3

# Usage in Template

Then, in the JFinal template engine, you can use the _res object to get internationalized data.

#(_res.get("msg"))
1

The above code configures I18nInterceptor to intercept action requests and allows the Freemarker template files to use an object named _res to get internationalized data. The specific workflow of I18nInterceptor is as follows:

  1. Tries to get the locale parameter from the request using controller.getPara("_locale"). If obtained, it saves it in a cookie.

  2. If controller.getPara("_locale") does not get a value, it tries to get the locale parameter from controller.getCookie("_locale").

  3. If the above two steps still don't yield a locale parameter value, the value of I18n.defaultLocale is used as the locale.

  4. Using the locale value obtained in the previous steps, I18n.use(locale) is called to get a Res object. This Res object is then passed to the view using controller.setAttr("_res", res).

  5. If I18nInterceptor.isSwitchView is set to true, it will also change the rendered view, enabling the overall template file to switch. Details can be checked in the source code.

# Customization

The variable names "_locale" and "_res" used in I18nInterceptor can be specified when creating the I18nInterceptor object. If not specified, default values will be used. You can also extend I18nInterceptor and override methods like getLocalPara, getResName, and getBaseName to implement more personalized features.

# Advanced Usage

In some web systems, the page requires a lot of text to be internationalized, and the CSS and HTML may also vary greatly due to internationalization. For such use-cases, you can create multiple sets of internationalized views with the same name and categorize these views in subdirectories based on locale. Finally, use the I18nInterceptor to dynamically switch views based on the locale. You just need to set I18nInterceptor.isSwitchView to true to achieve this, saving time and effort.

Last Updated: 9/22/2023, 7:42:33 AM